package com.cx.scheduledtask;

import com.cx.constant.ProjectStatus;
import com.cx.mapper.ProjectMapper;
import com.cx.pojo.Project;
import com.cx.pojo.ToEmail;
import com.cx.util.ResultUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author: 晨曦
 * @Description: 项目定时任务
 * @DateTime: 2025/4/5 19:29
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class ProjectTask {
    private final ProjectMapper projectMapper;
    private final JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    @Scheduled(cron = "0 */1 * * * ?") // 每分钟触发一次
    public void processTimeoutProject() {
        log.info("处理超时项目：{}", LocalDateTime.now());
        // time = 当前时间-5分钟，如果time > endTime： 项目结束时间则表示该项目为超时项目
        LocalDateTime time = LocalDateTime.now().plusMinutes(-5);
        List<Project> projectList = projectMapper.getByStatusAndTimeProjectTimeLT(ProjectStatus.COMPLETED, time);
        if (projectList != null && !projectList.isEmpty()) {
            projectList.forEach(project -> {
                commonEmail(new ToEmail(new String[]{
                        "1922671176@qq.com",
                        "2027404633@qq.com",
                        "1055329983@qq.com",
                        "3552768872@qq.com",
                        "1908926204@qq.com"
                }, "处理超时项目", project.getName() + "即将超时，请及时处理"));
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    Project pro = projectMapper.selectById(project.getId());
                    if (!Objects.equals(pro.getStatus(), ProjectStatus.COMPLETED)) {
                        project.setStatus(ProjectStatus.TIME_OUT_PROJECT);
                        projectMapper.update(project);
                    }
                }
            });
        }
    }

    public ResultUtil commonEmail(ToEmail toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        try {
            mailSender.send(message);
            return ResultUtil.success(toEmail.getTos(), "发送邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return ResultUtil.error("发送邮件失败");
        }

    }

}
